import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import Layout from '@/layout'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    menus: [],
    buttons: [],
    orgname:''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  SET_ORGNAME:(state,orgname)=>{
    state.orgname = orgname
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password,mobile,code } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password,mobile:mobile,code:code  }).then(response => {
        commit('SET_TOKEN', response.data.token)
        setToken(response.data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({}).then(response => {
        if (!response) {
          return reject('Verification failed, please Login again.')
        }
        var _menus = "[]"
        var menus=eval(_menus)
        var buttons =[]

        menus.push(
          {
            path: '/',
            component: Layout,
            redirect: '/home',
            hidden:true,
            children: [{
              path: 'home',
              name: 'home',
              component: () => import('@/views/home/index'),
              meta: { title: '首页', icon: 'el-icon-s-home', affix: true }
            }]
          }
        )

        const list=response.data.menus

        for( var i = 0 ; i < list.length ; i++ ){
          var menu={
            path: list[i].path,
            component: Layout,
            redirect: list[i].path,
            name: list[i].menuName,
            alwaysShow: true,
            meta: {
              title: list[i].menuName,
              icon: list[i].icon,
              index: list[i].path
            },
            children: []
          }
          for(var j=0;j < list[i].children.length;j++){
            menu.children.push(
              {
                path: list[i].children[j].path,
                name: list[i].children[j].menuName,
                component: loadView(list[i].children[j].component),
                meta: {
                  title: list[i].children[j].menuName,
                  index: list[i].path + '/' + list[i].children[j].path
                },
                target:list[i].children[j].isOpen==1?false:true
              }
            )
            for(var k=0;k<list[i].children[j].children.length;k++){
               buttons.push(list[i].children[j].children[k].perms)
            }
          }
          menus.push(menu)
        }

        commit('SET_NAME', response.data.name)
        commit('SET_AVATAR', require('@/assets/head.png'))
        commit('SET_MENUS', menus)
        commit('SET_BUTTONS', buttons)
        commit('SET_ORGNAME',response.data.roles[0]?response.data.roles[0].name:'')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export const loadView = (view) => {
  return (resolve) => require([`@/views${view}`], resolve)
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
